import Music from './logic/music'
import DataBus from './databus'

const ctx = canvas.getContext('2d')
const databus = new DataBus(ctx)

/**
 * 游戏主函数
 */
export default class Main {
  constructor() {
    // 维护当前requestAnimationFrame的id
    this.aniId = 0
    this.restart()
  }

  restart() {
    databus.reset()

    this.music = new Music()

    this.bindLoop = this.loop.bind(this)
    this.hasEventBind = false

    // 清除上一局的动画
    window.cancelAnimationFrame(this.aniId)

    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }

  touchStartHandler(e) {
    e.preventDefault()
    const x = e.touches[0].clientX
    const y = e.touches[0].clientY
    databus.click(x, y)
  }
  touchMoveHandler(e) {
    e.preventDefault()
    const x = e.touches[0].clientX
    const y = e.touches[0].clientY
    databus.moving(x, y)
  }
  touchEndHandler(e) {
    e.preventDefault()
    const x = e.changedTouches[0].clientX
    const y = e.changedTouches[0].clientY
    databus.moveEnd(x, y)
  }

  /**
   * canvas重绘函数
   * 每一帧重新绘制所有的需要展示的元素
   */
  render() {
    ctx.clearRect(0, 0, canvas.width, canvas.height)

    databus.render(ctx)

    if (!this.hasEventBind) {
      this.hasEventBind = true
      this.touchStartDelegate = this.touchStartHandler.bind(this)
      canvas.addEventListener('touchstart', this.touchStartDelegate)
      this.touchMoveDelegate = this.touchMoveHandler.bind(this)
      canvas.addEventListener('touchmove', this.touchMoveDelegate)
      this.touchEndDelegate = this.touchEndHandler.bind(this)
      canvas.addEventListener('touchend', this.touchEndDelegate)
    }
  }

  // 游戏逻辑更新主函数
  update() {
    databus.update()
  }

  // 实现游戏帧循环
  loop() {
    databus.frame++
    this.update()
    this.render()

    this.aniId = window.requestAnimationFrame(
      this.bindLoop,
      canvas
    )
  }
}